package com.xuan.web;
import com.alibaba.druid.util.StringUtils;
import com.xuan.dao.UserDao;
import com.xuan.model.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns="/servlet/UserAction")
@SuppressWarnings("all")
public class UserAction extends HttpServlet {
    private UserDao empDao=new UserDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String act = request.getParameter("act");
        switch (act){
            case "updatePassword":
                String password = request.getParameter("password");
                String password1 = request.getParameter("password1");
                if(StringUtils.isEmpty(password)) {
                    forward(request,response,"msg","密码不能省略.","../WEB-INF/jsp/updatePassword1.jsp");
                    return;
                }
                if(!password.matches("\\w{4,8}")) {
                    forward(request,response,"msg","密码应该为4-8位英文或数字.","../WEB-INF/jsp/updatePassword1.jsp");
                    return;
                }
                if(!password.equals(password1)) {
                    forward(request,response,"msg","您的密码2次输入不一致。","../WEB-INF/jsp/updatePassword1.jsp");
                    return;
                }
                User emp= (User) request.getSession().getAttribute("loginEmp");
                emp.setPassword(password);
                forward(request,response,"msg",
                        empDao.updatePassword(emp)?"修改密码成功":"修改密码失败",
                        "../WEB-INF/jsp/updatePassword1.jsp");
                break;
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String act = request.getParameter("act");
        switch (act){
            case "updatePassword":
                forward(request,response,"../WEB-INF/jsp/updatePassword1.jsp");
                break;
            case "findPassword":
                forward(request,response,"../WEB-INF/jsp/findPassword1.jsp");
                break;
        }

    }

    private void forward(HttpServletRequest request, HttpServletResponse response, String url) throws ServletException, IOException {
        request.getRequestDispatcher(url).forward(request, response);
    }

    private void forward(HttpServletRequest request, HttpServletResponse response, String key,Object value, String url) throws ServletException, IOException {
        request.setAttribute(key, value);
        request.getRequestDispatcher(url).forward(request, response);
    }

}
